package com.epoch.serviceconsumer.service.impl;

import bean.response.ResponseBean;
import bean.response.ResultEnum;
import com.epoch.serviceconsumer.bean.Consumer;
import com.epoch.serviceconsumer.dao.ConsumerDao;
import com.epoch.serviceconsumer.service.ConsumerService;
import com.epoch.zuul.auth.dao.CsRoleDao;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import utils.Base;
import utils.FileType;
import utils.ResultInfoUtil;
import utils.validcode.DataValid;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;

/**
 * @author admin
 */
@Service
@Slf4j
public class ConsumerServiceImpl implements ConsumerService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ConsumerDao consumerDao;

//    @Autowired
//    private CsRoleDao csRoleDao;

    @Override
    public ResponseBean getById(String csId) {
        Consumer consumer = consumerDao.getById(csId);
//        consumer.setRoleName(csRoleDao.getRoleByCsId(consumer.getId()));
        return ResultInfoUtil.buildSuccess(ResultEnum.OK, "获取用户信息成功",consumer);
    }

    @Override
    public Consumer getByCsPhone(String csPhone) {
        return consumerDao.getByCsPhone(csPhone);
    }

    @Override
    public ResponseBean csInfoComplete(Consumer completeConsumer, HttpServletRequest request) {
        //判断当前用户
        String token;
        String csPhone;
        try{
            token = request.getHeader("Authorization");
//            csPhone = Objects.requireNonNull(JwtUtil.parseJWT(token)).getId();
        }catch (Exception e){
            e.printStackTrace();
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"用户未登录");
        }

        if (completeConsumer.getCsEmail() != null && !DataValid.emailValid(completeConsumer.getCsEmail())){
            //邮箱不正确
            logger.info("用户信息完善失败【邮箱不正确】{}", completeConsumer);
            return ResultInfoUtil.buildError("用户信息完善失败,邮箱无效");
        }else{
            //进行信息插入
            consumerDao.csInfoComplete(completeConsumer.getCsId(),
                    completeConsumer.getCsName(),
                    completeConsumer.getCsEmail(),
                    completeConsumer.getCsSex(),
                    completeConsumer.getCsAge(),
                    completeConsumer.getCsBirth(),
                    completeConsumer.getCsPhoto(),
                    completeConsumer.getCsInfo());
            logger.info("用户信息完善成功 {}", consumerDao.getById(completeConsumer.getCsId()));
            return ResultInfoUtil.buildSuccess(ResultEnum.OK,"信息完善成功",consumerDao.getById(completeConsumer.getCsId()));
        }
    }

    @Override
    public ResponseBean changePwd(HashMap<String, String> map){
        //判断该用户是否存在
        String csPhone = map.get("csPhone");
        String oldPwd = map.get("oldPwd");
        String newPwd = map.get("newPwd");
        System.out.println(oldPwd);
        oldPwd = Base.encode(oldPwd);
        System.out.println(csPhone);
        System.out.println(newPwd);
        try {
            newPwd = Base.decode(newPwd);
        } catch (UnsupportedEncodingException e) {

        }
        Consumer currentConsumer = consumerDao.getByCsPhone(csPhone);
        if (currentConsumer == null){
            logger.info("用户修改密码失败，该用户不存在");
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"用户修改密码失败，该用户不存在");
        }else if (!currentConsumer.getCsPwd().equals(oldPwd)) {
            //用户密码错误，不能进行密码修改
            logger.info("用户修改密码失败，密码错误");
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"用户修改密码失败，密码错误");
        } else{
            //对密码进行验证
            if(!DataValid.pwdValid(newPwd)){
                //密码验证不通过
                logger.info("用户修改密码失败，密码不符合规范");
                return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"用户修改密码失败，密码不符合规范");
            }else{
                //密码验证通过，密码加密后修改密码
                newPwd = Base.encode(newPwd);
                consumerDao.changePwd(csPhone, Base.encode(newPwd));
                logger.info("用户修改密码成功 {}", consumerDao.getByCsPhone(csPhone));
                return ResultInfoUtil.buildSuccess(ResultEnum.OK,"用户修改密码成功",consumerDao.getByCsPhone(csPhone));
            }
        }
    }

    @Override
    public ResponseBean deleteCsByCsId(String csId) {
        //校验非空
        if (csId == null || consumerDao.getById(csId) == null){
            return ResultInfoUtil.buildError(ResultEnum.BAD_REQUEST,"用户ID为空或用户不存在，删除失败");
        }else{
            return ResultInfoUtil.buildSuccess(ResultEnum.OK,"删除用户成功",consumerDao.deleteCsByCsId(csId));
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean addPhoto(MultipartFile multipartFile, String csId, HttpServletResponse response) {
        StringBuffer stringBuffer = new StringBuffer();
        //文件存在且不为空
        if (multipartFile != null && !multipartFile.isEmpty()){
            //判断文件类型
            InputStream inputStream;
            try{
                inputStream = multipartFile.getInputStream();
                String fileType = FileType.getFileType(inputStream);
                System.out.println("consumerServiceImpl addPhoto filetype is "+ fileType);
                if (fileType == "png" || fileType == "jpg"){
                    //过滤文件
                    //将文件保存到数据库
                    System.out.println("设置头像内容：");
                    System.out.println("============进行头像上传============");
                    consumerDao.updatePhoto(csId, multipartFile.getBytes(), fileType);
                    System.out.println("============头像上传结束============");
                    //进行头像返回
                    byte[] byteImage = consumerDao.getById(csId).getPhoto();
                    if (byteImage != null){
                        inputStream = new ByteArrayInputStream(byteImage);
                        try {
                            BufferedImage image = ImageIO.read(inputStream);
                            if (fileType == "jpg"){
                                ImageIO.write(image,fileType,response.getOutputStream());
                            }else {
                                ImageIO.write(image,"png",response.getOutputStream());
                            }

                            return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取头像成功");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    return ResultInfoUtil.buildSuccess(ResultEnum.OK,"头像上传成功");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultInfoUtil.buildError("头像为空，上传失败");
    }

    @Override
    public ResponseBean getPhoto(String csId, HttpServletResponse response) {
        byte[] byteImage = consumerDao.getById(csId).getPhoto();
        String photoType = consumerDao.getById(csId).getPhotoType();
        System.out.println("photoType: "+photoType);
        if (byteImage != null){
            InputStream inputStream = new ByteArrayInputStream(byteImage);
            try {
                BufferedImage image = ImageIO.read(inputStream);
                System.out.println(image.getMinX());
                if (photoType == "jpg"){
                    ImageIO.write(image,photoType,response.getOutputStream());
                }else {
                    ImageIO.write(image,"png",response.getOutputStream());
                }

                return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取头像成功");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ResultInfoUtil.buildSuccess(ResultEnum.BAD_REQUEST,"获取头像失败");
    }

    @Override
    public ResponseBean getConsumerList() {
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"获取用户基本信息成功（用户管理）",consumerDao.getConsumerList());
    }

    @Override
    public ResponseBean addManager(Consumer consumer) {
        consumer.setCsId("U"+consumer.getCsPhone());
        consumer.setCsPwd(Base.encode(consumer.getCsPwd()));
        System.out.println(consumer.toString());
        consumerDao.addManager(consumer);
        return ResultInfoUtil.buildSuccess(ResultEnum.OK,"添加管理员成功", consumerDao.getByCsPhone(consumer.getCsPhone()));
    }

    @Override
    public ResponseBean updateCsUseState(HashMap <String, Object> map) {
        Integer useState = (Integer) map.get("state");
        String csId = (String) map.get("csId");
        if (useState == 0 || useState == 1){
            consumerDao.updateCsUseState(csId,useState);
            return ResultInfoUtil.buildSuccess(ResultEnum.OK,"修改用户使用状态成功",consumerDao.getById(csId));
        }else {
            return ResultInfoUtil.buildError(ResultEnum.INVALID_REQUEST,"状态码异常");
        }
    }

}
